package api

import (
	repo "gin-blog/app/repositories"
	"gin-blog/utils/errcode"
	"gin-blog/utils/helper"
	"gin-blog/utils/re"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"net/http"
)

type Auth struct {
	Username string `valid:"Required; MaxSize(50)"`
	Password string `valid:"Required; MaxSize(50)"`
}

func GetAuth(c *gin.Context)  {
	username := c.PostForm("username")
	password := c.PostForm("password")
	code := errcode.INVALID_PARAMS
	msg := errcode.GetMsg(code)
	data := make(map[string]interface{})

	valid := validation.Validation{}
	var auth = Auth{
		Username: username,
		Password: password,
	}

	ok, _ := valid.Valid(auth)

	if ok {
		isok := repo.CheckAuth(username, password)
		if isok {
			token, err := helper.GenerateToken(username, password)
			if err != nil {
				code = errcode.ERROR_AUTH_TOKEN
				msg = errcode.GetMsg(code)
			} else {
				data["token"] = token
				code = errcode.SUCCESS
				msg = errcode.GetMsg(code)
			}
		} else {
			code = errcode.ERROR_AUTH_LOGIN
			msg = errcode.GetMsg(code)
		}
	} else {
		msg = re.RequestErrors(valid.Errors)
	}

	resp := re.Gin{C: c}
	resp.Response(http.StatusOK, code, msg, data)
}

